﻿using System;
using LuaInterface;
using UnityEngine;

public static class LuaHelper
{
    public static void LogStackDump(IntPtr L)
    {
        var top = LuaDLL.lua_gettop(L);
        Debug.LogError("stack length : " + top);
        for (int i = 1; i <= top; i++)
        {
            LuaTypes type = LuaDLL.lua_type(L, i);
            
            switch (type)
            {
                case LuaTypes.LUA_TNIL:
                    LogError(i, "lua nil");
                    break;
                case LuaTypes.LUA_TNONE:
                    LogError(i, "lua None");
                    break;
                case LuaTypes.LUA_TBOOLEAN:
                    LogError(i, "(bool) " + LuaDLL.lua_toboolean(L, i));
                    break;
                case LuaTypes.LUA_TLIGHTUSERDATA:
                    // IntPtr lightUserdata = LuaDLL.get
                    // LuaDLL.lua_pushlightuserdata(L, );
                    LogError(i, LuaTypes.LUA_TLIGHTUSERDATA.ToString());
                    break;
                case LuaTypes.LUA_TNUMBER:
                    LogError(i, LuaDLL.lua_tonumber(L, i).ToString());
                    break;
                case LuaTypes.LUA_TSTRING:
                    LogError(i, LuaDLL.lua_tostring(L, i));
                    break;
                case LuaTypes.LUA_TTABLE:
                    LogError(i, LuaTypes.LUA_TTABLE.ToString());
                    break;
                case LuaTypes.LUA_TFUNCTION:
                    LogError(i, LuaTypes.LUA_TFUNCTION.ToString());
                    break;
                case LuaTypes.LUA_TUSERDATA:
                    int reference = LuaDLL.tolua_getmetatableref(L, 1);

                    if (reference > 0)
                    {
                        Type t = LuaStatic.GetClassType(L, reference);
                        LogError(i, LuaTypes.LUA_TUSERDATA.ToString() + " : " + t.FullName);
                    }
                    else
                    {                        
                        LogError(i, LuaTypes.LUA_TUSERDATA.ToString() + " : " + "type not register or null");
                    }
                    break;
                case LuaTypes.LUA_TTHREAD:
                    LogError(i, LuaTypes.LUA_TTHREAD.ToString());
                    break;
                default:
                    LogError(i, "没有对应类型");
                    break;
            }
        }
    }

    static void LogError(int stackPos, string msg)
    {
        Debug.LogError($"pos : {stackPos}, value : {msg}");
    }
}